package com.ogawa.jopai.devicemanage.activity

import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.base.BaseVMActivity
import com.ogawa.base.utils.DividerGridItemDecoration
import com.ogawa.base.utils.SpUtil
import com.ogawa.base.utils.toPx
import com.ogawa.jopai.devicemanage.adapter.DeviceManageAdapter
import com.ogawa.jopai.devicemanage.bean.ChangeUserDeviceInfoRequest
import com.ogawa.jopai.devicemanage.dialog.DeviceReNameDialog
import com.ogawa.jopai.devicemanage.viewmodel.DeviceManageViewModel
import com.ogawa.joypal.devicemanage.R
import com.ogawa.projectcommon.bean.EventRefreshDeviceManageActivity
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.projectcommon.utils.ProjectSpUtils
import com.ogawa.projectcommon.utils.ProjectUtils
import kotlinx.android.synthetic.main.activity_device_manage.*


@Route(path = UrlPathConstant.ACTIVITY_DEVICEMANAGE_MAIN)
class DeviceManageActivity : BaseVMActivity<DeviceManageViewModel>() {
    private lateinit var mAdapter: DeviceManageAdapter
    override fun getLayoutId(): Int {
        return R.layout.activity_device_manage
    }

    override fun providerVMClass(): Class<DeviceManageViewModel>? {
        return DeviceManageViewModel::class.java
    }

    override fun observeVM() {

        mViewModel.mGetDeviceShareResponseList.observe(this, Observer {
            if (it != null && it.size > 0) {
                setSecondRightImg(R.drawable.img_msg_s)
            } else {
                setSecondRightImg(R.drawable.img_msg_n)
            }
        })

        mViewModel.beanList.observe(this, Observer {
            it?.run {
                mAdapter.setNewData(it)
                val sns = StringBuffer()
                for (item in it) {
//                    mViewModel.getChairStatus(item.sn, "0")
                    sns.append(item.sn).append(",")
                }
                if (sns.length > 0) {
                    sns.deleteCharAt(sns.length - 1)
                }
                if (sns.length > 0) {
                    mViewModel.getChairStatusCol(sns.toString())
                }
            }
            setAddVis(mAdapter.data.isNotEmpty())
        })
        mViewModel.mDeviceShareResponse.observe(this, Observer {
            ToastUtils.showShort(getString(R.string.share_success))
            mViewModel.getUserDevice()
        })
        mViewModel.mChangeUserDeviceInfoResponse.observe(this, Observer {
            ToastUtils.showShort(getString(R.string.change_success))
            mViewModel.getUserDevice()
        })
        mViewModel.mDeleteUserDeviceResponse.observe(this, Observer {
            ToastUtils.showShort(getString(R.string.delete_device_success))
            mViewModel.getUserDevice()
        })
        mViewModel.mGetChairStatusResponse.observe(this, Observer {
            for (index in mAdapter.data.indices) {
                var item = mAdapter.data[index]
                if (item.sn == it.sn) {
                    item.isOnline = it.code
                    mAdapter.notifyItemChanged(index)
                    break
                }
            }
        })
        mViewModel.mGetChairStatusColResponse.observe(this, Observer {
            for (index in mAdapter.data.indices) {
                var item = mAdapter.data[index]
                for (resItem in it) {
                    if (item.sn == resItem.sn) {
                        if (resItem.conn_status == "0") {
                            item.isOnline = "02"
                        } else if (resItem.conn_status == "1") {
                            item.isOnline = "01"
                        }
                        break
                    }
                }
            }
            mAdapter.notifyDataSetChanged()
        })
    }

    override fun initView() {
        super.initView()
        setTitle(resources.getString(R.string.device_manager))
        setBackVis(false)
        setPerVis(true)
        setMsgVis(true)
//        setAddVis(true)

        setPerOnclick(View.OnClickListener {
            ARouter.getInstance().build(UrlPathConstant.ACTIVITY_USER_INFO).navigation()
        })
        setMsgOnclick(View.OnClickListener {
            val userInfo = ProjectSpUtils.getUserInfo()
            if (userInfo.isVisitor) {
                ToastUtils.showShort(getString(R.string.visitor_no_pro_edit_user))
                return@OnClickListener
            }
            ARouter.getInstance().build(UrlPathConstant.ACTIVITY_DEVICEMANAGE_MESSAGE).navigation()
        })
        setAddOnclick(View.OnClickListener {
            selectSupportDevice()
        })

        initRv()
        swipeRefresh.setOnRefreshListener {
            swipeRefresh.isRefreshing = false
            mViewModel.getUserDevice()
        }
        mViewModel.getUserDevice()
        LiveEventBus.get(EventRefreshDeviceManageActivity::class.java)
            .observe(this, Observer {
                mViewModel.getUserDevice()
            })
    }

    override fun onResume() {
        super.onResume()
        val userInfo = ProjectSpUtils.getUserInfo()
        if (userInfo.isVisitor) {
            return
        }
        mViewModel.getDeviceShare()
    }


    private fun initRv() {
        deviceManageRv.layoutManager = GridLayoutManager(this, 2)
        deviceManageRv.setHasFixedSize(true)
        mAdapter = DeviceManageAdapter()
        val userInfo = ProjectSpUtils.getUserInfo()
        mAdapter.isVisitor = userInfo.isVisitor
        mAdapter.setOnItemClickListener { _, _, position ->
            val userDeviceBean = mAdapter.data[position]
            if (userDeviceBean.isOnline == "01"){
                SpUtil.set(SpUtil.SN, userDeviceBean.sn)
                ProjectUtils.jumpToDeviceActivity(userDeviceBean.typeCode)
            }else{
                ToastUtils.showShort(getString(R.string.chair_no_online_tips))
            }

        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val userDeviceBean = mAdapter.data[position]
            when (view.id) {
                R.id.itemDeviceManageShareBt -> {
                    ARouter.getInstance().build(UrlPathConstant.ACTIVITY_SHARE_DEVICE)
                        .withString("sn", userDeviceBean.sn)
                        .navigation()

                }
                R.id.itemDeviceManageReNameBt -> {
                    DeviceReNameDialog()
                        .show(mActivity, userDeviceBean.name,
                            object : DeviceReNameDialog.DeviceReNameDialogListener {
                                override fun successOnclick(newName: String) {
                                    var request = ChangeUserDeviceInfoRequest()
                                    request.id = userDeviceBean.id
//                                    request.userId = userDeviceBean.userId
                                    request.name = newName
                                    request.readUuid = userDeviceBean.readUuid
                                    request.writerUuid = userDeviceBean.writerUuid
                                    request.peripheralUuid = userDeviceBean.peripheralUuid
                                    request.iosUuid = userDeviceBean.iosUuid
                                    request.androidUuid = userDeviceBean.androidUuid
                                    request.bluetoothName = userDeviceBean.bluetoothName
                                    request.label = userDeviceBean.label

                                    mViewModel.changeUserDevices(userDeviceBean.deviceId, request)

                                }

                            })
                }
                R.id.itemDeviceManageDelBt -> {
                    AlertDialog.Builder(mActivity)
                        .setTitle(getString(R.string.sure_del_device_title))
                        .setNegativeButton(R.string.cancel) { dialog, _ ->
                            dialog.dismiss()
                        }
                        .setPositiveButton(R.string.confirm) { dialog, _ ->
                            mViewModel.userDevicesDelete(userDeviceBean.deviceId)
                            dialog.dismiss()
                        }
                        .show()
                }
            }
        }
        val emptyView =
            LayoutInflater.from(this).inflate(R.layout.empty_device_manage_add_device, null)
        emptyView.setPadding(0, 0, 0, 0)
        emptyView.findViewById<TextView>(R.id.addDeviceBt).setOnClickListener {
            selectSupportDevice()
        }
        deviceManageRv.addItemDecoration(DividerGridItemDecoration(2, 20.toPx, 20.toPx, true))
        mAdapter.emptyView = emptyView
        deviceManageRv.adapter = mAdapter
    }

    private fun selectSupportDevice() {
//        var userInfo = ProjectSpUtils.getUserInfo()
//        if (userInfo.isVisitor){
//            var mEntityUserDevice = EntityUserDevice()
//            mEntityUserDevice.userId = userInfo.user.id
//            var timeStr= System.currentTimeMillis().toString()
//            mEntityUserDevice.deviceName = timeStr
//            mEntityUserDevice.deviceSN = timeStr
//            mEntityUserDevice.deviceId = timeStr
//            OperationDB().addEntityUserDevice(mEntityUserDevice)
//            mViewModel.getUserDevice()
//            return
//        }
        ARouter.getInstance().build(UrlPathConstant.ACTIVITY_DEVICEMANAGE_CHOOSE_DEVICE)
            .navigation()
    }


    var backTime: Long = 0
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            val time = System.currentTimeMillis() - backTime
            backTime = System.currentTimeMillis()
            if (time < 2000 * 1) {
                finish()
            } else {
                ToastUtils.showShort(getString(R.string.ret_back_app))
            }
            return true
        }
        return super.onKeyUp(keyCode, event)
    }


}